package com.stud.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.stud.common.constant.CacheConstants;
import com.stud.common.core.redis.RedisCache;
import com.stud.common.exception.ServiceException;
import com.stud.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author Stud
 * @title XXXXX
 * @desription XXXXX
 * @data 2022-11-25 11:50
 */
@Slf4j
public class PhoneMessageUtil {
    private static final String ACCESS_KEY_ID = "LTAI5tCKhVoRMsk9vcVKTwKG";
    private static final String ACCESS_KEY_SECRET = "EGLSnDErTnJpgPxbCDfNL7p5VQRRHR";
    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";
    private static final String REGION_ID = "cn-zhangjiakou";
    private static final String SIGN_NAME = "Stud";
    private static final String TEMPLATE_CODE = "SMS_261175072";

    public static boolean send(JSONObject params, String... phoneNumbers) {
        if (Objects.isNull(phoneNumbers) || phoneNumbers.length == 0) {
            log.info("手机号为空");
            return false;
        }

        DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setSysEndpoint(ENDPOINT);
        request.setSignName(SIGN_NAME);
        request.setTemplateCode(TEMPLATE_CODE);
        request.setPhoneNumbers(StringUtils.join(phoneNumbers));
        request.setTemplateParam(JSON.toJSONString(params));

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            log.info(new Gson().toJson(response));
        } catch (ClientException e) {
            log.error(e.getMessage());
        }

        return true;
    }

    /**
     * 校验手机验证码 有问题中断进程直接抛异常
     */
    public static boolean validateMessageCode(String uuid, String phone, String code) {
        if (StringUtils.isBlank(uuid) || StringUtils.isBlank(code)) {
            throw new ServiceException("参数异常");
        }

        uuid = Toolkit.xssEncode(uuid);
        code = Toolkit.xssEncode(code);

        String verifyKey = CacheConstants.MESSAGE_CODE_KEY + uuid + phone;

        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
        String captcha = redisCache.getCacheObject(verifyKey);

        if (captcha == null) {
            throw new ServiceException("短信验证码已失效");
        }
        if (!Objects.equals(captcha, code)) {
            throw new ServiceException("短信验证码错误");
        }
        return true;
    }

}
